//
//  Player.cpp
//  dot
//
//  Created by zz on 2019/6/16.
//

#include "Player.hpp"



Player* Player::create(Vec2 pos){

    auto player = new Player();
    if(player&&player->init(pos)){

        player->autorelease();
        return player;

    }else{

        CC_SAFE_DELETE(player);
        return NULL;
    }
}


bool Player::init(Vec2 pos){
    
    Sprite::initWithFile("round.png");
    
    this->setContentSize(Size(120,120));
    this->setColor(Color3B::WHITE);
    this->p1 = Sprite::create("Dot.png");
    this->p1->setAnchorPoint(Vec2(0.5,0.5));
    this->p1->setColor(Color3B::RED);
    this->p1->setPosition(Vec2(0,60));
    this->addChild(this->p1);
   
    this->r = this->p1->getContentSize().width/2;
    
    this->po1 = Vec2(0,0.5);
    this->po2 = Vec2(1,0.5);
    
    
    this->p2 = Sprite::create("Dot.png");
     this->p2->setAnchorPoint(Vec2(0.5,0.5));
    this->p2->setColor(Color3B::YELLOW);
    this->p2->setPosition(Vec2(120,60));
    this->addChild(this->p2);
    this->setAnchorPoint(this->po1);
    this->setPosition(pos);
    this->currentAnp = false;
    this->currentDir = 1;
    this->speed=2.0f;
    auto ro = RotateBy::create(this->speed, this->currentDir*360);
    auto rep = RepeatForever::create(ro);
    this->runAction(rep);
    return true;
}


void Player::changeDir(){
    
    this->currentDir=-this->currentDir;
    this->createRound();
}
void Player::changeAnPoint(){
    
    this->currentAnp=!this->currentAnp; //更改锚点记录
    this->createRound();  //根据不同的锚点创建y旋转运动
}


void Player::createRound(){

    this->stopAllActions();  //开始新的运动前必须先停止之前的旋转运动。
    Vec2 pos =Vec2::ZERO;
    //根据当前的锚点，来切换不同的锚点
    if(this->currentAnp){
       pos =  this->convertToWorldSpace(this->p2->getPosition()); //坐标转化  本地坐标->世界坐标
       this->setAnchorPoint(this->po2);
    }else{
       pos = this->convertToWorldSpace(this->p1->getPosition());
       this->setAnchorPoint(this->po1);
    }
    
    this->setPosition(pos);
    auto ro = RotateBy::create(this->speed, this->currentDir*360);

    auto rep = RepeatForever::create(ro);
    this->runAction(rep);
}

Vec2 Player::getActionPoint(){
    
    return this->currentAnp ? this->convertToWorldSpace(this->p2->getPosition()): this->convertToWorldSpace(this->p1->getPosition());
}


float Player::getR(){
    
    return this->r;
}

void Player::addSpeed(float v){
    
    this->speed+=v;
}
